<?php

namespace App\Library\Logic;

use App\Library\Requests\Pet\PetAddRequest;
use App\Library\Requests\Pet\PetEditRequest;
use App\Library\Requests\Pet\PetPageRequest;
use App\Models\PetModel;
use Illuminate\Database\Eloquent\Model;

class PetLogic extends PetModel
{
    /**
     * paging
     * @param PetPageRequest $request
     * @return array
     */
    public function paging(PetPageRequest $request): array
    {
        $builder = $this->newQuery()->where(['user_id' => USERID, 'pet_is_delete' => 2])->orderByDesc('pet_id');
        if (!is_null($request->name)) {
            $name = strip_tags(trim($request->name));
            if (!empty($name)) {
                $builder->where('pet_code', 'like', "%$name%");
                $builder->orWhere('pet_name', 'like', "%$name%");
                $builder->orWhere('pet_box', 'like', "%$name%");
            }
            $request->offsetUnset('name');
        }
        $paginate = helpBuilder($builder->with('image'), $request)->paginate($request->limit);
        foreach ($paginate->items() as $v) {
            $v->img_url = $v->image->img_url ?? null;
            unsetObject($v, 'image');
        }
        return paginate($paginate);
    }

    /**
     * add
     * @param PetAddRequest $request
     * @return void
     */
    public function add(PetAddRequest $request): void
    {
        $pet = self::insertForModel(array_merge($this->saveCom($request), [
            'petCode' => $this->petCode(),
            'createdAt' => time(),
            'updatedAt' => time(),
            'userId' => USERID,
        ]));
        $this->saveImg($pet);
    }

    /**
     * edit
     * @param PetEditRequest $request
     * @param Model $pet
     * @return void
     */
    public function edit(PetEditRequest $request, Model $pet): void
    {
        $pet = self::updateForModel($this->saveCom($request), $pet);
        $this->saveImg($pet);
    }

    public function petCode(): string
    {
        return date("ymdHis") . random(10, 1);
    }

    /**
     * saveCom
     * @param PetAddRequest $request
     * @return array
     */
    private function saveCom(PetAddRequest $request): array
    {
        $array = handleRequest($request);
        foreach ($array as $k => $v) {
            if ($k === 'contentImgIdJson') $v = json_encode($array['contentImgIdJson']);
            $array['pet' . ucfirst($k)] = $v;
            unset($array[$k]);
        }
        return $array;
    }

    /**
     * saveImg
     * @param Model $pet
     * @return void
     */
    private function saveImg(Model $pet): void
    {
        if (is_null($pet->pet_content_img_id_json)) return;
        ShopImageLogic::query()->whereIn('img_id', json_decode($pet->pet_content_img_id_json, true))
            ->where(['user_main_id' => MAINID, 'img_source_type' => 8])
            ->update(['img_source_id' => $pet->pet_id, 'img_is_cover' => 0]);
    }
}
